<?php
class ProjectsController extends AppController {
	public $name = 'Projects';
	public $uses=array('Project','User','Status');
	
	
	
	
	function admin_index(){
		$this->Session->write('CurrentModule',$this->uses[0]);
		//get filter field
		$filterField=array(
		$this->uses[0].'.name'=>_resource('project name',true),
		$this->uses[0].'.description'=>_resource('project description',true)
		);
		//	get status
		$this->set("statuses",$this->Status->find('list'));
		//default status
		if(!$this->Session->check($this->uses[0].'.status_id')){			 
			//get default status
			$status=$this->Status->find('first',array('conditions'=>array('default'=>1)));
			if(!empty($status))$this->Session->write($this->uses[0].'.status_id',$status['Status']['id']);
		}
		
		$this->set('filterField',$filterField);
		$this->render('admin_index','ajax');
	}

	function admin_lists(){
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>$this->uses[0].'.created desc',
				'page'=>1,
				'recursive'=>1,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
				'status_id'=>$this->Session->read($this->uses[0].'.status_id')
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);
		}

		$user=$this->user;

		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//===================================================================
		
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...
		$paginate=$this->Session->read($this->uses[0]);
		if($this->Session->check($this->uses[0].'.status_id') && $this->Session->read($this->uses[0].'.status_id')>0){
			$paginate['conditions']['Status.id']=$this->Session->read($this->uses[0].'.status_id');
		}	
		
		if($this->user['group_id']!=1 && $this->user['group_id']!=4){
			//get project by users
			$paginate['conditions']['OR']=array(
				'LEFT('.$this->uses[0].'.users,'.(strlen($this->user['id'])+1).')'=>array($this->user['id'].',',$this->user['id']),				
				'RIGHT('.$this->uses[0].'.users,'.(strlen($this->user['id'])+1).')'=>array(','.$this->user['id'],$this->user['id']),
				$this->uses[0].'.users LIKE'=>'%,'.$this->user['id'].',%'
			);
			//t($paginate);
		}
		
		//join table
		$this->Project->bindModel(array('belongsTo'=>array('Manager'=>array('className'=>'Users','foreignKey'=>'manager'))));
		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$this->paginate=$paginate
		;
		$data0=$this->paginate($this->uses[0]);
		
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);

		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website.
		$this->render('admin_lists','ajax');
	}

	function admin_add($locale=null){
		//su dung khi site co chuc nang da ngon ngu==========================
		//neu khong truyen vao ngon ngu thi ngon ngu mac dinh cua data duoc them vao se la ngon ngu duoc doc tu session
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		//khai bao ngon ngu cua model, khi do, ngon ngu cua data duoc luu vao database la $locale
		$this->{$this->uses[0]}->locale=$locale;
		//====================================================================
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		$isInsert=false;
		//get user
		$user=$this->user;
		if(!empty($this->data)){
			$data=$this->data;
			$data[$this->uses[0]]['user_id']=$this->user['id'];
			if($this->{$this->uses[0]}->create($data) && $this->{$this->uses[0]}->validates()){
				//get field
				if(isset($data[$this->uses[0]]['fields']))$data[$this->uses[0]]['fields']=implode(',',$data[$this->uses[0]]['fields']);

				
				//user create will join
				$userjoins=array($this->user['id']=>$this->user['id']);				
				//manager join
				if(!isset($data[$this->uses[0]]['manager']))$data[$this->uses[0]]['manager']=$this->user['id'];
				$userjoins[$data[$this->uses[0]]['manager']]=$data[$this->uses[0]]['manager'];
				
				//userjoin
				if(isset($data[$this->uses[0]]['users']))$userjoins=$userjoins+$data[$this->uses[0]]['users'];				
				//qa
				$qa=array();
				if(isset($data[$this->uses[0]]['qa'])){					
					$userjoins=$userjoins+$data[$this->uses[0]]['qa'];
					$qa=$data[$this->uses[0]]['qa'];
				}			
				
				//add user
				$data[$this->uses[0]]['users']=implode(',',$userjoins);
				//add qa
				$data[$this->uses[0]]['qa']=implode(',',$qa);
				
				//get default status
				$status=$this->Status->find('first',array('conditions'=>array('default'=>1)));
				if(isset($status['Status']['id']))$data[$this->uses[0]]['status_id']=$status['Status']['id'];
				if($this->{$this->uses[0]}->save($data)) {
					
					$projId=$this->{$this->uses[0]}->getInsertID();
					App::import('Model','ProjectUser');
					$ProjectUser =& new ProjectUser();
					foreach($userjoins as $k=>$v){
						$data=array('project_id'=>$projId,'user_id'=>$v);
						$ProjectUser->create($data);
						$ProjectUser->save($data); 
					}
					
					//permission for manager
					if(isset($data[$this->uses[0]]['manager'])){
						App::import('Model','User');
						$User =& new User();
						$user=$User->read(null,$data[$this->uses[0]]['manager']);
						$proj=$this->{$this->uses[0]}->read(null,$projId);
						//create aco						
        				$root = $this->Acl->Aco->node('controllers/Projects/admin_edit');
        				$root = $root[0];
						$this->Acl->Aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => 'Projectsadmin_edit'.$projId));
						$newaco=$this->Acl->Aco->save();
						$this->Acl->allow($user,'projectsadmin_edit'.$projId);
						
					}
					$this->Session->write('message',_resource('insert data successful',true));
					$this->redirectAjaxTo('projects/lists','listContent');
					
					$this->data=null;					
					$isInsert=true;
					
				} else {
					$this->Session->write('error',_resource('can not insert data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}

		//get all field
		App::import('Model','Field');
		$Field =& new Field();
		$fields=$Field->find('all');
		$this->set('fields',$fields);
		//get all user except group 1
		App::import('Model','User');
		$User =& new User();
		$users=$User->find('all',array('conditions'=>array('group_id <>'=>1,'group_id <>'=>4,'User.id <>'=>$this->Session->read('User.User.id'))));
		$this->set('users',$users);
		
		//get all prior	
		App::import('Model','Priority');
		$prio =& new Priority();	
		$priors=$prio->find('list',array('order'=>'view_order desc'));
		$this->set('priors',$priors);
		//get default prior
		$defaultPrior=$prio->find('first',array('conditions'=>array('default'=>1)));
		$defaultPriorId=0;
		if(isset($defaultPrior['Priority']['id']))$defaultPriorId=$defaultPrior['Priority']['id'];
		$this->set('defaultPriorId',$defaultPriorId);

		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
	}

	function admin_edit($id=null,$locale=null){
		$projectinfo=$this->getPermission(0,intval($id));	
		if(!isset($projectinfo['Project'])){
			$this->Session->write('error',_resource('can not edit project, not have permission',true));			
			if($this->Session->check('Task.project_id'))
				$this->redirectAjaxTo('tasks/lists','listContent');
			else $this->redirectAjaxTo('projects/lists','listContent');	
		}
		//check is manager
		if(!Configure::read('Session.isAdmin') && !Configure::read('Session.isSa') && !Configure::read('Session.isManager')){
			$this->Session->write('error',_resource('can not edit project, not have permission',true));			
			if($this->Session->check('Task.project_id'))
				$this->redirectAjaxTo('tasks/lists','listContent');
			else $this->redirectAjaxTo('projects/lists','listContent');	
		}
		else if(!empty($this->data)){
			$data=$this->data;			
			if($this->{$this->uses[0]}->validates($data)){											
				//get fields
				if(isset($data[$this->uses[0]]['fields']))$data[$this->uses[0]]['fields']=implode(',',$data[$this->uses[0]]['fields']);
				else $data[$this->uses[0]]['fields']='';
				//t($data[$this->uses[0]]['fields']);
				//user create will join
				$userjoins=array($this->user['id']=>$this->user['id']);				
				//manager join
				if(isset($data[$this->uses[0]]['manager']))$userjoins[$data[$this->uses[0]]['manager']]=$data[$this->uses[0]]['manager'];
				//userjoin
				if(isset($data[$this->uses[0]]['users']))$userjoins=$userjoins+$data[$this->uses[0]]['users'];				
				//qa
				$qa=array();
				if(isset($data[$this->uses[0]]['qa'])){					
					$userjoins=$userjoins+$data[$this->uses[0]]['qa'];
					$qa=$data[$this->uses[0]]['qa'];
				}	
				
				//add user
				$data[$this->uses[0]]['users']=implode(',',$userjoins);
				//add qa
				$data[$this->uses[0]]['qa']=implode(',',$qa);
			
				//process edit for user
				$oldusers=explode(',',$data[$this->uses[0]]['oldusers']);
				//if(!empty($data[$this->uses[0]]['oldusers']))$userjoins=array_merge($userjoins,explode(',',$data[$this->uses[0]]['oldusers']));
				//t($data,0);
				$denyusers=array_diff($oldusers,$userjoins);
				$allowusers=array_diff($userjoins,$oldusers);
				//t(array_diff($oldusers,$userjoins));
				//t($denyusers,0);
				//t($allowusers,0);
				if($this->{$this->uses[0]}->save($data)) {
					
					$projId=$id;
					
					
					//edit manager permission
					if(isset($data[$this->uses[0]]['manager']) && $data[$this->uses[0]]['oldmanager']!=$data[$this->uses[0]]['manager']){
												
						App::import('Model','User');
						$User =& new User();
						
						//get aco
						$aconame='Projectsadmin_edit'.$projId;
						$aco = $this->Acl->Aco->node($aconame);
       					if(empty($aco)){
       						//create aco
       						$root = $this->Acl->Aco->node('controllers/Projects/admin_edit');
       						$this->Acl->Aco->create(array('parent_id' => $root[0]['Aco']['id'], 'model' => null, 'alias' => $aconame));
							$aco=$this->Acl->Aco->save();
							
       					}
						//deny old manager
						$user=$User->read(null,$data[$this->uses[0]]['oldmanager']);
						if(!empty($user)){
							$aro=$this->Acl->Aro->node($user);
							$this->Project->query('delete from aros_acos where aro_id='.$aro[0]['Aro']['id'].' and aco_id='.$aco[0]['Aco']['id']);
						}	
						//permission for new manager					
						$user=$User->read(null,$data[$this->uses[0]]['manager']);						
						if(!empty($user)){							
							$this->Acl->allow($user,$aconame);
						}
					}
					
					//edit user join permission
					App::import('Model','ProjectUser');
					$ProjectUser =& new ProjectUser();
					//deny old user
					foreach($denyusers as $k=>$v){
						$ProjectUser->updateAll(array('ProjectUser.published'=>0),array('ProjectUser.user_id'=>$v,'ProjectUser.project_id'=>$projId));						
					}
					
					//allow new user
					
					foreach($allowusers as $k=>$v){
						
						//check exist
						$user=$ProjectUser->find('first',array('conditions'=>array('ProjectUser.user_id'=>$v,'ProjectUser.project_id'=>$projId)));
						if(!empty($user)){
							$ProjectUser->updateAll(array('ProjectUser.published'=>1),array('ProjectUser.user_id'=>$v,'ProjectUser.project_id'=>$projId));
						}
						else{
							$data=array('project_id'=>$projId,'user_id'=>$v);
							$ProjectUser->create($data);
							$ProjectUser->save($data);	
						}						
					}
					
					
					$this->Session->write('message',_resource('update data successful',true));
					if($this->Session->check('Task.project_id'))
						$this->redirectAjaxTo('tasks/lists','listContent');
					else $this->redirectAjaxTo('projects/lists','listContent');	
					$this->data=null;					
					$isInsert=true;
					
					

				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			

				
				$data=$projectinfo['Project'];
				$data[$this->uses[0]]['oldusers']=$data[$this->uses[0]]['users'];
				$data[$this->uses[0]]['oldmanager']=$data[$this->uses[0]]['manager'];
				
				//user join		
				$this->data=$data;						
			
		}
		//get all field
		App::import('Model','Field');
		$Field =& new Field();
		$fields=$Field->find('all');
		$this->set('fields',$fields);
		//get all user except group 1
		App::import('Model','User');
		$User =& new User();
		$users=$User->find('all',array('conditions'=>array('group_id <>'=>1,'User.id <>'=>$this->Session->read('User.User.id'))));
		$this->set('users',$users);
		
		//get all status		
		App::import('Model','Status');
		$status =& new Status();	
		$statuses=$status->find('list',array('order'=>'view_order desc'));
		$this->set('statuses',$statuses);
		//get all prior	
		App::import('Model','Priority');
		$prio =& new Priority();	
			$priors=$prio->find('list',array('order'=>'view_order desc'));
			$this->set('priors',$priors);
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
	}

	function admin_delete($id = null) {		
		if(Configure::read('Session.isSa') || Configure::read('Session.isAdmin')){
			$this->Session->delete('error');
			//if is submit:		
			if($this->request->is('post')){
				$id_arr=array_keys($_POST['check']);
			} else {
				$id_arr=null;
			}
			//if url
			if(intval($id)){
				$id_arr[]=$id;
			}
			if(count($id_arr)>0){
				//Xoa nhieu record
				$this->{$this->uses[0]}->deleteAll(array($this->uses[0].'.id'=>$id_arr),false);			
			} else {
				$this->Session->write('error',_resource('no information to delete',true));
			}
		}
		else{
			$this->Session->write('error',_resource('you have not permission',true));
		}
		$this->admin_lists();		
	}
	

	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}

	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);

		$this->admin_lists();
	}

	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			//$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';
				$this->Session->write($this->uses[0].'.page',1);				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}
	
	function admin_status($statusid=0){
		//status
		$statusid=intval($statusid);
		$this->Session->write($this->uses[0].'.status_id',$statusid);		
		$this->Session->write($this->uses[0].'.page',1);
		$this->admin_lists();
	}
	

}
?>
